import { BASEURL, TOKEN } from '@/assets/js/config.js'
import { storage } from './utils'
import { useStore } from '@/store'
const store = useStore()
// 请求错误提示
// eslint-disable-next-line node/handle-callback-err
const showError = (error, message, successCallback) => {
  uni.showToast({
    title: message,
    duration: 2000,
    icon: 'none',
    mask: true,
    success: res => {
      successCallback && typeof successCallback === 'function' && successCallback()
    }
  })
}
// 500错误提示
const globalError = response => {
  uni.showModal({
    title: String(response.code),
    content: response.msg,
    confirmText: '确定',
    showCancel: false
  })
}
const interceptorsRequest = (method, url, data, type, header = {}) => {
  return {
    method,
    url,
    data,
    type,
    header
  }
}
const request = ({ method = 'get', url, data, type, header = {} }) => {
  const params = interceptorsRequest(method, url, data, type, header)
  params.header['Content-Type'] = 'application/json; charset=utf-8'
  const TokenStore = storage.get(TOKEN) || store.state.token
  if (TokenStore) {
    params.header.Authorization = TokenStore
  }
  params.header.endpoint = 'PICO'
  // #ifdef H5
  params.header.platform = 'H5'
  // #endif
  // #ifdef MP-WEIXIN
  params.header.platform = 'MP'
  // #endif
  return new Promise((resolve, reject) => {
    let url = ''
    params.type = 'public'
    url = BASEURL + '/' + params.type + '/v1' + params.url
    uni.request({
      method,
      url,
      header: params.header,
      data: params.data,
      withCredentials: true,
      success: res => {
        const resData = res.data
        if (res.statusCode === 200) {
          if (
            resData.code === 600603 ||
            resData.code === 600401 ||
            resData.code === 600403 ||
            resData.code === 600402
          ) {
            // 登录过期过期逻辑，在全局的profile请求不需要登录
            const _method = method.toLocaleLowerCase()
            if (params.url === '/profile' && params.data && _method === 'get') {
              store.commit('resetState', '')
              store.commit('setProfile', null)
              storage.clear()
            } else {
              storage.remove(TOKEN)
              uni.reLaunch({
                url: '/pages/index'
              })
            }
            reject(resData)
          } else if (resData.code === 0) {
            resolve(resData)
          } else {
            showError('糟糕！出错了', resData.msg || '请联系客服')
            resolve(resData)
          }
        } else {
          reject(resData.msg)
          globalError({
            code: 500,
            msg: '500'
          })
        }
      },
      fail: err => {
        uni.showModal({
          title: '网络',
          content: '网络出现问题，请检查网络是否连接畅通！',
          confirmText: '确定',
          showCancel: false
        })
        reject(err)
      }
    })
  })
}

export default request
